<template>
  <div>
    <h3>电影列表</h3>
    <input v-model="searchQuery" placeholder="搜索电影" />
    <button @click="showAddMovieForm = true">添加电影</button>

    <div v-if="showAddMovieForm || editMovieId!== null">
      <h4 v-if="showAddMovieForm">添加新电影</h4>
      <h4 v-else>编辑电影</h4>
      <input v-model="currentMovie.title" placeholder="电影标题" required />
      <input v-model="currentMovie.director" placeholder="导演" required />
      <input v-model="newMovieActor" placeholder="演员" @keyup.enter="addActor" />
      <ul>
        <li v-for="(actor, index) in currentMovie.actors" :key="index">
          {{ actor }}
          <button @click="removeActor(index)">删除</button>
        </li>
      </ul>
      <input type="date" v-model="currentMovie.releaseDate" required />
      <textarea v-model="currentMovie.summary" placeholder="简介" required></textarea>
      <button @click="saveMovie">保存</button>
      <button @click="cancelEdit">取消</button>
    </div>

    <ul>
      <li v-for="movie in filteredMovies" :key="movie.id" class="movie-item">
        <div class="movie-info">
          <h4>{{ movie.title }}</h4>
          <div class="movie-details">
            <p><strong>导演:</strong> {{ movie.director }}</p>
            <p><strong>演员:</strong> {{ movie.actors.join(', ') }}</p>
            <p><strong>日期:</strong> {{ formatDate(movie.releaseDate) }}</p>
            <p><strong>简介:</strong> {{ movie.summary }}</p>
          </div>
          <div class="movie-actions">
            <button class="edit" @click="editMovie(movie)">编辑</button>
            <button class="delete" @click="deleteMovie(movie)">删除</button>
          </div>
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
import { reactive, toRefs, computed } from 'vue';

export default {
  name: 'MovieList',
  setup() {
    const state = reactive({
      searchQuery: '',
      showAddMovieForm: false,
      newMovieActor: '',
      editMovieId: null,
      currentMovie: {
        id: null,
        title: '',
        director: '',
        actors: [],
        releaseDate: '',
        summary: '',
        poster: null
      },
      movies: [
        { id: 1, title: '毒液：最后一舞', director: '凯莉.马塞尔', actors: ['汤姆.哈迪', '贾冰'], releaseDate: '2023-01-01', summary: '超级IP“毒液”迎来系列终章，10月23日全国大银幕上映。被军方神秘研究组织抓捕，刚踏上逃亡之路的毒液与埃迪，又遭遇“共生体之神”纳尔麾下外星异噬体们猎杀，劲敌环伺，毒液百变附体极限突围。毒液与埃迪背水一战，生死难料，而牺牲自己是否会成为拯救对方的唯一方式？', poster: null },
        { id: 2, title: '爱你很久很久', director: '赖孟杰', actors: ['李沫', '曹佑宁','娄峻硕'], releaseDate: '2023-02-01', summary: '你的青春里有没有一个忘不掉的人？阳光明媚的高中生王晓夏（李沐 饰）在一次偶然中对天才转校生程奕（曹佑宁 饰）一见钟情，无法克制的心跳，让晓夏开启高调追爱模式。而从小一起长大默默守护着她的柚子（娄峻硕 饰）也决定为自己争取一次。一边是天降男神，一边是竹马守护，十七岁的少年都怀揣着最炙热的爱意，晓夏又该如何抉择？爱是给勇敢者的奖励，2024年冬天第一部爱情电影，一定要和最最最爱的人一起看⋯.', poster: null },
        { id: 3, title: '志愿军：存亡之战', director: '陈凯歌', actors: ['朱一龙', '辛伯青','张子枫'], releaseDate: '2023-02-01', summary: '陈凯歌执导，《志愿军》三部曲第二部《志愿军：存亡之战》将聚焦铁原阻击战。震撼巨制还原铁原硝烟，铁血不灭谱写英雄故事，一场存亡之战，一支英雄铁军！抗美援朝战争第五次战役的转移阶段，铁原阻击战正式打响，中国人民志愿军第63军2.5万将士与近5万“联合国军”展开激战。志愿军将士们浴血奋战，终于把敌军打上了谈判桌。面前，武装到牙齿的敌军步步迫近；身后，是数十万正在转移的主力部队，生死存亡，在此一战。1个小时，敌军的4500吨炮弹向我军一个师的阵地倾泻而至，12昼夜，步坦炮协同的敌军数次冲锋.⋯.志愿军战士们发扬“钉子战术”，把自己变成一根钉子，狠狠地钉在阵地上！暗藏机巧的防御工事，神出鬼没的地道突袭，招招见血的贴身肉搏，“人在阵地在”的誓言响彻铁原战场，63军全体将士一起，在铁原构成了一道冲不破的“铁长城”。', poster: null },
      ]
    });

    const filteredMovies = computed(() =>
      state.movies.filter(movie =>
        movie.title.toLowerCase().includes(state.searchQuery.toLowerCase())
      )
    );

    const editMovie = (movie) => {
      state.editMovieId = movie.id;
      state.currentMovie = {...movie };
      state.showAddMovieForm = true;
    };

    const deleteMovie = (movie) => {
      const index = state.movies.findIndex((m) => m.id === movie.id);
      if (index!== -1) {
        state.movies.splice(index, 1);
      }
      state.editMovieId = null;
      state.showAddMovieForm = false;
    };

    const formatDate = (dateString) => new Date(dateString).toLocaleDateString();

    const addActor = () => {
      if (state.newMovieActor.trim()) {
        state.currentMovie.actors.push(state.newMovieActor.trim());
        state.newMovieActor = '';
      }
    };

    const removeActor = (index) => {
      state.currentMovie.actors.splice(index, 1);
    };

    const saveMovie = () => {
      if (state.editMovieId!== null) {
        const movieIndex = state.movies.findIndex((m) => m.id === state.editMovieId);
        if (movieIndex!== -1) {
          state.movies[movieIndex] = {...state.currentMovie };
          state.editMovieId = null;
        }
      } else {
        const newMovie = {...state.currentMovie };
        newMovie.id = Date.now().toString();
        state.movies.push(newMovie);
      }
      state.currentMovie = {
        id: null,
        title: '',
        director: '',
        actors: [],
        releaseDate: '',
        summary: '',
        poster: null
      };
      state.newMovieActor = '';
      state.showAddMovieForm = false;
    };

    const cancelEdit = () => {
      state.currentMovie = {
        id: null,
        title: '',
        director: '',
        actors: [],
        releaseDate: '',
        summary: '',
        poster: null
      };
      state.newMovieActor = '';
      state.showAddMovieForm = false;
      state.editMovieId = null;
    };

    return {
     ...toRefs(state),
      filteredMovies,
      editMovie,
      deleteMovie,
      formatDate,
      addActor,
      removeActor,
      saveMovie,
      cancelEdit
    };
  }
};
</script>

<style scoped>
h3 {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 20px;
}

input {
  width: 100%;
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-bottom: 20px;
  box-sizing: border-box;
}

ul {
  list-style: none;
  padding: 0;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.movie-item {
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.movie-info {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-width: 0;
}

.movie-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}

.movie-details {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.movie-details p {
  margin: 0;
  font-size: 14px;
  color: #555;
}

.movie-details strong {
  color: #333;
}

.movie-actions {
  display: flex;
  gap: 10px;
}

button {
  padding: 8px 16px;
  font-size: 14px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #007bff;
  color: white;
}

button.edit {
  background-color: #28a745;
  color: white;
}

button.delete {
  background-color: #dc3545;
  color: white;
}
</style>